//
//  AppDelegate.m
//  Finance
//
//  Created by cheng xiang on 12-12-9.
//  Copyright (c) 2012年 cheng xiang. All rights reserved.
//

#import "AppDelegate.h"
#import "MultiThreading.h"
#import "AnalysisJson.h"

@implementation AppDelegate

@synthesize version = _version;
@synthesize app_version = _app_version, autoRefresh = _autoRefresh, sendNotification = _sendNotification;
@synthesize trackViewURL = _trackViewURL;
@synthesize loginSessionID = _loginSessionID;
@synthesize loginName = _loginname;
@synthesize registercode =_registercode;
@synthesize registerseq = _registerseq;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:1.5];
    _version = [[UIDevice currentDevice].systemVersion doubleValue];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
    NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]stringByAppendingPathComponent:@"AppInfo.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        NSLog(@"%@",dic[@"version"]);
        _app_version = dic[@"version"];
        _autoRefresh = dic[@"autoRefresh"];
        _sendNotification = dic[@"sendNotification"];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        dic[@"version"] = @"1.0.0";
        dic[@"autoRefresh"] = APP_TRUE;
        dic[@"sendNotification"] = APP_TRUE;
        _app_version = @"1.0.0";
        _autoRefresh = APP_TRUE;
        _sendNotification = APP_TRUE;
        [dic writeToFile:plistPath atomically:YES];
    }
    
    if ([_autoRefresh isEqualToString:APP_TRUE]) {
        [self onCheckVersion];
    }
    
    [self changeToolBarBackground];
    
   // [self checkautologin];
    return YES;
}

-(void)changeToolBarBackground
{
    UITabBarController *tabBarController =
    (UITabBarController *)self.window.rootViewController;
    UIImage *img = [UIImage imageNamed:@"Layer.png"];
    [tabBarController.tabBar setBackgroundImage:img];
    tabBarController.tabBar.opaque = YES;

    UINavigationController *navController = [tabBarController moreNavigationController];
    UIImage *root_image = [UIImage imageNamed:@"toolbar.jpg"];
    [navController.navigationBar setBackgroundImage:root_image forBarMetrics:UIBarMetricsDefault];
    tabBarController.customizableViewControllers = nil;
    tabBarController.moreNavigationController.delegate = self;
    
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    UIView *tableView = navController.topViewController.view;
//    ((UITableView *)tableView).separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//    ((UITableView *)tableView).separatorColor = [UIColor blackColor];

    [tableView setBackgroundColor:bk];
}

- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
    
    UINavigationBar *morenavbar = navigationController.navigationBar;
    UINavigationItem *morenavitem = morenavbar.topItem;
    /* We don't need Edit button in More screen. */
    morenavitem.rightBarButtonItem = nil;
    
    [navigationController setHidesBottomBarWhenPushed:YES];

//    [self hideTabBar:(UITabBarController *)self.window.rootViewController];   
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UINavigationBar *morenavbar = navigationController.navigationBar;
    UINavigationItem *morenavitem = morenavbar.topItem;
    /* We don't need Edit button in More screen. */
    morenavitem.rightBarButtonItem = nil;
    
    [navigationController setHidesBottomBarWhenPushed:NO];
    //[self showTabBar:(UITabBarController *)self.window.rootViewController];
}

// Method implementations
- (void)hideTabBar:(UITabBarController *) tabbarcontroller
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)];
        }
    }
    
    [UIView commitAnimations];
}

- (BOOL)tabbarShowInView:(UITabBarController *)tabbarcontroller
{
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            if (view.frame.origin.y == 480) {
                return NO;
            }else{
                return YES;
            }
        }
    }
    return YES;
}

- (void)hideTabBarWithoutAnimation:(UITabBarController *)tabbarcontroller
{
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)];
        }
    }
}

- (void)showTabBar:(UITabBarController *) tabbarcontroller
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        NSLog(@"%@", view);
        
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 431, view.frame.size.width, view.frame.size.height)];
            
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 431)];
        }
    }
    
    [UIView commitAnimations];
}

- (void)showTabBarWithoutAnimation:(UITabBarController *)tabbarcontroller
{
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        NSLog(@"%@", view);
        
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 431, view.frame.size.width, view.frame.size.height)];
            
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 431)];
        }
    }
}

- (void)onCheckVersion
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W116"];
    NSDictionary *body = [self PackageBody];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    //发送报文
    [self getTableData: requestJson];
}

//每次组报文需要实现类似组body的方法
- (NSDictionary *)PackageBody
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    return dic;
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryAppVersion"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)requestCallBack:(NSDictionary *)rdic
{
    NSObject *body = rdic[@"body"];
    if([body isKindOfClass:[NSDictionary class]] )
    {
        NSString *lastestVersion = [(NSDictionary *)body objectForKey:@"latestVersion"];
        _trackViewURL = [(NSDictionary *)body objectForKey:@"downloadUrl"];
        //NSString *forceUpdate = [(NSDictionary *)body objectForKey:@"forceUpdate"];
        if (![lastestVersion isEqualToString:_app_version]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            [alert show];
        }
    }
   
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        UIApplication *application = [UIApplication sharedApplication];
        [application openURL:[NSURL URLWithString:_trackViewURL]];
    }
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

-(void)writeplist:(NSString*)strkey PlistValue:(NSString*)strvalue
{

   
}

-(NSDictionary*)readplist
{

    NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]stringByAppendingPathComponent:@"Setting.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    {
        NSMutableDictionary* test = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        
        return  test;
    }
    
//    NSArray* arrdocpath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString* docpath = [arrdocpath objectAtIndex:0];
//    
//    NSString* filepath = [docpath stringByAppendingString:@"AppInfo.plist"];
//    
//    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath])
//    {
//
//    }

    return nil;
}

-(void)checkautologin
{
    NSDictionary* plist = [self readplist];
    if(plist.count != 0 && [[plist objectForKey:@"islogin"] intValue] == 1)
    {
        NSString* username = [plist objectForKey:@"username"];
        NSString* userpassword = [plist objectForKey:@"password"];

        //组请求报文
        NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W106"];
        NSDictionary *body = [self setLoginPackketBody:username UserPassword:userpassword];
        
        NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
//        NSString *jsonString = [[NSString alloc] initWithData:requestJson encoding:NSUTF8StringEncoding];
        
        //发送报文
        [self sendUserLoginInfo: requestJson];
    }
}

-(NSDictionary*)setLoginPackketBody:(NSString*)userName  UserPassword:(NSString*)userPassword
{
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
    [dict setObject:userName forKey:@"userName"];
    [dict setObject:userPassword forKey:@"password"];
    
    return dict;
}


-(void)sendUserLoginInfo:(NSData*)jsonData
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"UserLogin"] toObject:self callBack:@selector(requestUserLoginCallBack:) withBody:jsonData];
}

-(void)requestUserLoginCallBack:(NSDictionary *)dic
{
    NSDictionary* body = dic[@"body"];    
    if([body isEqual:[NSNull null]] !=1 &&  body.count != 0)
    {
        self.loginSessionID = body[@"sessionId"];
        self.loginName = body[@"userName"];
    }
    
}

-(void)writeplist:(NSString*)keys  Value:(NSString*)values
{
    NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"setting" ofType:@"plist"];
    
    NSMutableDictionary* plistdic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistpath];
    [plistdic setObject:values forKey:keys];
    
    NSArray* arrdocpath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docpath = [arrdocpath objectAtIndex:0];
    
    NSString* filepath = [docpath stringByAppendingString:@"setting.plist"];
    [plistdic writeToFile:filepath atomically:YES];
    
    NSMutableDictionary* test = [[NSMutableDictionary alloc] initWithContentsOfFile:filepath];
    NSLog(@"test2 = %@",test);
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
